<?php
/**
 * @Description 文件处理
 * @Sonkwl Xiong
 * @Date 2022/09/20 16:39:35
 */
define('MULTIPART_BOUNDARY', '--------------------------'.microtime(true));
define('FORM_FIELD', 'uploaded_file');
class upfile{
    static public $url="http://127.0.0.1/2022/mobile/php/";
    static public $path="files/";
    static public $crossUrl="";

    /** 
     * 生成存储路径
    */
    static public function CheckDir(){
        if(!is_dir(self::$path)){
            if(!mkdir(self::$path,0777,true)){
                jsoner::Response(array("res"=>"NG","message"=>"创建文件目录失败"));
            }
        }
        if(!is_dir(self::$path.'/'.date("Ymd"))){
            if(!mkdir(self::$path.'/'.date("Ymd"),0777,true)){
                jsoner::Response(array("res"=>"NG","message"=>"创建日期目录失败"));
            }
        }
    }
    
    /**
     * 處理上傳文件
     * input:$file:$_FILES,$types:array('jpg','jpeg'),$size:1M
     * output:url
     */
    static public function Save($file,$types,$size){
        self::CheckDir();
        try {
            // $file=$_FILES["s_file"];
            $filename=$file["name"];
            $full=explode(".",$filename);
            $filetype=end($full);
            if(!in_array($filetype,$types)){
                jsoner::Response(array("res"=>"NG","message"=>"上传文件格式错误,请上传".implode(",",$types)."文件"));
            }
            if($file["size"]>1024*1024*$size){
                jsoner::Response(array("res"=>"NG","message"=>"文件不能大于".$size."M"));
            }
            $dir=date("Ymd");
            if(!is_dir(self::$path."/".$dir)){
                mkdir(self::$path."/".$dir,0777);
            }
            $filepath=self::$path.'/'.$dir.'/'.date("YmdHis").'.'.$filetype;
            move_uploaded_file($file["tmp_name"],$filepath);
            return self::$url.$filepath;
        }catch (\Throwable $th) {
            jsoner::Response(array("res"=>"NG","message"=>"文件保存失败"));
        }
    }
    /**
     * 處理上傳文件
     * input:$file:$_FILES,$types:array('jpg','jpeg'),$size:1M
     * output:url
     */
    static public function SaveOnly($file,$types,$size,$rstr){
        self::CheckDir();
        try {
            // $file=$_FILES["s_file"];
            $filename=$file["name"];
            $full=explode(".",$filename);
            $filetype=end($full);
            if(!in_array($filetype,$types)){
                jsoner::Response(array("res"=>"NG","message"=>"上传文件格式错误,请上传".implode(",",$types)."文件"));
            }
            if($file["size"]>1024*1024*$size){
                jsoner::Response(array("res"=>"NG","message"=>"文件不能大于".$size."M"));
            }
            $dir=date("Ymd");
            if(!is_dir(self::$path."/".$dir)){
                mkdir(self::$path."/".$dir,0777);
            }
            $filepath=self::$path.'/'.$dir.'/'.$rstr.'_'.date("YmdHis").random_int(1,10000).'.'.$filetype;
            move_uploaded_file($file["tmp_name"],$filepath);
            return self::$url.$filepath;
        }catch (\Throwable $th) {
            jsoner::Response(array("res"=>"NG","message"=>"文件保存失败"));
        }
    }
    /** 
     * 处理图片数据返回文件路径
    */
    static public function Img($data){
        self::CheckDir();
        $reg = '/data:image\/(\w+?);base64,(.+)$/si';
        preg_match($reg,$data,$match_result);
        $path=self::$path.'/'.date("Ymd").'/'.date("His").random_int(1,10000).random_int(1,10000).'.jpg';//亿分之一概率相同
        // echo $path;
        try {
            if(count($match_result)<3){
                return $data;
            }
            file_put_contents($path,base64_decode($match_result[2]));
            return self::$url.$path;
        } catch (\Throwable $th) {
            jsoner::Response(array("res"=>"NG","message"=>"文件保存失败"));
            // return $data;
        }
    }
    /**
    * 處理PDF文件並返回文件存儲路徑 
    */
    static public function Pdf($data){
        self::CheckDir();
        $reg = '/data:application\/(\w+?);base64,(.+)$/si';
        preg_match($reg,$data,$match_result);
        $path=self::$path.'/'.date("Ymd").'/'.date("His").random_int(1,10000).random_int(1,10000).'.pdf';//亿分之一概率相同
        try {
            if(count($match_result)<3){
                return $data;
            }
            file_put_contents($path,base64_decode($match_result[2]));
            return self::$url.$path;
        } catch (\Throwable $th) {
            jsoner::Response(array("res"=>"NG","message"=>"文件保存失败"));
            // return $data;
        }
    }
    /** 
     * 处理图片数据返回文件路径
    */
    static public function ImgOnly($data,$s_no){
        self::CheckDir();
        $reg = '/data:image\/(\w+?);base64,(.+)$/si';
        preg_match($reg,$data,$match_result);
        $path=self::$path.'/'.date("Ymd").'/'.$s_no.'_'.date("His").random_int(1,10000).'.jpg';//亿分之一概率相同
        // echo $path;
        try {
            if(count($match_result)<3){
                return $data;
            }
            file_put_contents($path,base64_decode($match_result[2]));
            return self::$url.$path;
        } catch (\Throwable $th) {
            jsoner::Response(array("res"=>"NG","message"=>"文件保存失败"));
            // return $data;
        }
    }
    /**
    * 處理PDF文件並返回文件存儲路徑 
    */
    static public function PdfOnly($data,$s_no){
        self::CheckDir();
        $reg = '/data:application\/(\w+?);base64,(.+)$/si';
        preg_match($reg,$data,$match_result);
        $path=self::$path.'/'.date("Ymd").'/'.$s_no.'_'.date("His").random_int(1,10000).'.pdf';//亿分之一概率相同
        try {
            if(count($match_result)<3){
                return $data;
            }
            file_put_contents($path,base64_decode($match_result[2]));
            return self::$url.$path;
        } catch (\Throwable $th) {
            jsoner::Response(array("res"=>"NG","message"=>"文件保存失败"));
            // return $data;
        }
    }
    /**
     * 跨越提交文件
     */
    static public function SaveFileByCross($path){
        if(self::$crossUrl==""){
            jsoner::Response(array("res"=>"NG","message"=>"没有定义crossurl"));
        }
        $header = 'Content-Type: multipart/form-data; boundary='.MULTIPART_BOUNDARY;
        $file_data=file_get_contents($path);
        $content =  "--".MULTIPART_BOUNDARY."\r\n".
            "Content-disposition: form-data; name=\"".FORM_FIELD."\"; filename=\"".basename($path)."\"\r\n".
            "Content-Type: application/pdf\r\n\r\n".
            $file_data."\r\n";
        // add some POST fields to the request too: $_POST['foo'] = 'bar'
        $content .= "--".MULTIPART_BOUNDARY."\r\n".
                    "Content-disposition: form-data; name=\"foo\"\r\n\r\n".
                    "bar\r\n";
        // signal end of request (note the trailing "--")
        $content .= "--".MULTIPART_BOUNDARY."--\r\n";
        $context = stream_context_create(array(
            'http' => array(
                  'method' => 'POST',
                  'header' => $header,
                  'content' => $content,
            )
        ));
        return file_get_contents(self::$crossUrl, false, $context);
    }
}
?>